package com.example.iorder.user;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.domain.User;
import com.example.iorder.R;
import com.example.iorder.config.Config;
import com.example.iorder.util.DataStorage;
import com.example.iorder.util.HTTPClient;
import com.example.iorder.util.MessageManager;
import com.example.iorder.util.NavigationManager;

public class LoginUser extends Activity {
	private EditText phoneNumber;
	private EditText password;
	private Button btnLogin, btnCancel;

	// private dialogProgress progress;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_user);

		btnLogin = (Button) findViewById(R.id.btnLogin);
		phoneNumber = (EditText) findViewById(R.id.phoneNumber);
		password = (EditText) findViewById(R.id.password);
		this.setTitle("iOrder | User Login");

		// // Show loading indicator
		
		Button btnRegister = (Button)findViewById(R.id.btnRegister);
	    btnRegister.setOnClickListener(new View.OnClickListener() {

	      @Override
	      public void onClick(View view) {
	        Intent intent = new Intent(LoginUser.this, RegisterUser.class);
	        startActivity(intent);
	      }
	    });
	    
	    // Add the header navigation
	    RelativeLayout headerLayout = (RelativeLayout) findViewById(R.id.login_header);
	    NavigationManager.addHeaderNavigation(this, headerLayout);
	    NavigationManager.setCurrentTab(this, NavigationManager.TabButtons.Login);
	}

	@SuppressLint("HandlerLeak")
	private Handler searchOutputHandler = new Handler() {
		public void handleMessage(Message msg) {
			String newData = msg.getData().getString("searchResult");
			JSONArray records = null;

			try {
				JSONObject jsonObject = new JSONObject(newData);
				if (jsonObject.has("data") && jsonObject.has("msg")
						&& jsonObject.has("status")) {
					// Connection to server was successful and data was received
					if (jsonObject.get("status").toString().equals("200")) {
						// Als alles goed ging
						// door naar betalen -- intent

//						Intent intent = new Intent(LoginUser.this,
//						SampleActivity.class);
//						startActivity(intent);

						records = jsonObject.getJSONArray("data");
						for (int i = 0; i < records.length(); i++) {
							try {
								JSONObject row = records.getJSONObject(i);
								String userIdString = row.optString("ID");
								String userphoneNumberString = row.optString("PhoneNumber");
								String userFirstNameString = row.optString("Firstname");
								String userLastNameString = row.optString("Lastname");
								String userCityString = row.optString("City");
								String userEmailString = row.optString("EmailAddress");
								String userpasswordString = row .optString("Password");
								int Id = Integer.parseInt(userIdString);
								int phoneNumber = Integer.parseInt(userphoneNumberString);
								String password = userpasswordString;

								User newUser = new User(Id, phoneNumber, password);
								TextView guiId = (TextView) findViewById(R.id.Id);
								TextView guiphoneNumber = (TextView) findViewById(R.id.phoneNumber);
								TextView guipassword = (TextView) findViewById(R.id.password);

								guiId.setText(userIdString);
								guiphoneNumber.setText(userphoneNumberString);

								guipassword.setText(userpasswordString);

								DataStorage dataStorage = DataStorage.getInstance(getApplicationContext());
								dataStorage.saveStringElement("id", userIdString);
								dataStorage.saveStringElement("phonenumber", userphoneNumberString);
								dataStorage.saveStringElement("firstname", userFirstNameString);
								dataStorage.saveStringElement("lastname", userLastNameString);
								dataStorage.saveStringElement("city", userCityString);
								dataStorage.saveStringElement("email", userEmailString);
//								Toast.makeText(getBaseContext(),"Data0: " + dataStorage.getStringElement("id"), Toast.LENGTH_SHORT).show();
								finish();
								return;
							} catch (Exception e) {
								// Toast.makeText(getBaseContext(),
								// "Exception: " + e.getStackTrace(),
								// Toast.LENGTH_LONG).show();
							}
						}

					} else if (jsonObject.get("status").toString().equals("404")) {
						// Ongeldige gebruikersnaam en wachtwoord
						//"Backend server error: " + jsonObject.get("status").toString()
						String errorMessage = "Ongeldige combinatie van \ntelefoonnummer en wachtwoord!";
						Drawable image = getResources().getDrawable(R.drawable.error_2);
						View layout = MessageManager.getMessageView(getLayoutInflater(), image, errorMessage);
						
						Toast messageView = new Toast(getApplicationContext());
						messageView.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
						messageView.setDuration(Toast.LENGTH_SHORT);
						messageView.setView(layout);
						messageView.show();
						// progress.dismiss();
						// foutmelding
						showDialog(null, "Foute gegevens!");

					}
				} else {
					Toast.makeText(getBaseContext(), "Faulty backend server response!",	Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException jsnE) {
				String errorMessage = "JSON Error: " + jsnE.getMessage();
				if (newData.equals("Error: No network")) {
					errorMessage = getResources().getString(R.string.no_network_connection);
				}
				Toast.makeText(getBaseContext(), errorMessage, Toast.LENGTH_LONG).show();

			} catch (Exception e) {
				Toast.makeText(getBaseContext(), "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();

			}

			DataStorage dataStorage = DataStorage.getInstance(getApplicationContext());
			// Toast.makeText(getBaseContext(), "Data: " +
			// dataStorage.getStringElement("id"), Toast.LENGTH_SHORT).show();
		}

		private void showDialog(Object object, String string) {
			// TODO Auto-generated method stub

		}
	};

	public void login(View view) {

		final String fPhoneNumber = phoneNumber.getText().toString();
		final String fPassword = password.getText().toString();

		new Thread() {
			public void run() {
				Message msg = new Message();
				String path = "";
				HTTPClient httpClient = null;
				String searchResult = "";
				// int UserId = 11;

				try {
					path = Config.URL_USERS + "?phonenumber=" + fPhoneNumber
							+ "&password=" + fPassword;
					httpClient = new HTTPClient(getBaseContext());
					searchResult = httpClient.sendGETRequest(
							Config.IORDER_SERVER, path);

					msg.getData().putString("searchResult", searchResult);
					searchOutputHandler.sendMessage(msg);
				} catch (Exception e) {
					msg.getData().putString("exception", e.toString());
				}
			}
		}.start();

	}


}
